package cn.market.service.product.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import org.hibernate.SQLQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.market.bean.QueryResult;
import cn.market.bean.product.Brand;
import cn.market.service.base.DaoSupport;
import cn.market.service.product.BrandService;


@Service
@Transactional
public class BrandServiceBean extends DaoSupport<Brand> implements BrandService {

	@Override
	public void save(Brand entity) {
		entity.setCode(UUID.randomUUID().toString());
		super.save(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public QueryResult<Brand> getBrandsByParentIds(String where, int first,
			int max, Object[] params, LinkedHashMap<String, String> orderby) {
		QueryResult<Brand> qr = new QueryResult<Brand>();
		StringBuffer sql = new StringBuffer(" select name,code,logopath from brand ");
		sql.append(where);
		if(max !=-1 && first !=-1){
			sql.append(" limit ").append(first).append(",").append(max);
		}
		SQLQuery query = super.getSession().createSQLQuery(sql.toString());
		if(params != null && params.length>0){
			for(int i=0;i<params.length;i++)
				query.setParameter(String.valueOf(i+1), params[i]);
		}
		List list = query.list();
		List<Brand> brands = new ArrayList<Brand>();
		if(list != null && list.size()>0){
			for(int i=0;i<list.size();i++){
				Object [] obj = (Object [])list.get(i);
				Brand brand = new Brand();
				brand.setName(String.valueOf(obj[0]));
				brand.setCode(String.valueOf(obj[1]));
				brand.setLogopath(String.valueOf(obj[2]));
				brands.add(brand);
			}
		}
		qr.setResultlist(brands);
		//qr.setTotalrecord(super.getDateCount("Brand",where,params));
		sql = new StringBuffer("select count(1) from brand");
		sql.append(where);
		query = super.getSession().createSQLQuery(sql.toString());
		if(params != null && params.length>0){
			for(int i=0;i<params.length;i++)
				query.setParameter(String.valueOf(i+1), params[i]);
		}
		Long count = 0L;
		if(query.list() != null && query.list().size()>0){
			count = new Long(String.valueOf(query.list().get(0)));
			
		}
		qr.setTotalrecord(count);
		return qr;
	}
	
}
